package day21;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

/**
登录系统

 */


public class LoginSystem {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (true) {
			System.out.println("A注册	B登录	C退出");
			String option = scanner.next();
			if ("A".equalsIgnoreCase(option)) {
				System.out.println("请输入用户名：");
				String userInfo = scanner.next();
				userInfo += "\t";
				System.out.println("请输入密码：");
				userInfo += scanner.next();
				if (writeUserInfo(userInfo)) {	//写入文件
					System.out.println("注册成功");
				} else {
					System.out.println("注册失败");
				}
			} else if ("B".equalsIgnoreCase(option)) {
				System.out.println("请输入用户名：");
				String userInfo = scanner.next();
				userInfo += "\t";
				System.out.println("请输入密码：");
				userInfo += scanner.next();
				if (readUserInfo(userInfo)) {
					System.out.println("登录成功！");
				} else {
					System.out.println("登录失败！");
				}
			} else if ("C".equalsIgnoreCase(option)) {
				System.out.println("感谢使用，再见！");
				break;
			} else {
				System.out.print("输入有误，请重新输入：\t");
			}
		}
		scanner.close();
	}

	public static boolean writeUserInfo(String userInfo) {
		FileWriter out = null;
		BufferedWriter writer = null;
		try {
			//1. 找到目标文件
			File file = new File("users.txt");
			//2. 建立数据通道
			out = new FileWriter(file, true);	//追加
			writer = new BufferedWriter(out);
			//3. 写出文件数据
			writer.write(userInfo);
			writer.newLine();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally {
			try {
				if (writer != null) {
					//4. 关闭文件资源
					writer.close();
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return true;
	}
	
	public static boolean readUserInfo(String userInfo) {
		FileReader in = null;
		BufferedReader reader = null;
		try {
			//1. 找到目标文件
			File file = new File("users.txt");
			//2. 建立数据通道
			in = new FileReader(file);
			reader = new BufferedReader(in);
			String line = null;
			//3. 读取文件数据
			//4. 处理文件数据
			while ((line = reader.readLine()) != null) {
				if (line.equals(userInfo)) {
					return true;
				}
//				System.out.println(line);
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally {
			try {
				//5. 关闭文件资源
				if (reader != null) {
					reader.close();
				}
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return false;
	}
}
